home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / gnome-orca / orca / httpserver.py < prev    next >
Encoding:
Python Source  |  2009-04-13  |  5.1 KB  |  145 lines

  1. # Orca
  2. #
  3. # Copyright 2006-2008 Sun Microsystems Inc.
  4. #
  5. # This library is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU Library General Public
  7. # License as published by the Free Software Foundation; either
  8. # version 2 of the License, or (at your option) any later version.
  9. #
  10. # This library is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13. # Library General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Library General Public
  16. # License along with this library; if not, write to the
  17. # Free Software Foundation, Inc., Franklin Street, Fifth Floor,
  18. # Boston MA  02110-1301 USA.
  19.  
  20. """Provides an HTTP server for Orca.  This currently serves mainly as
  21. something that self-voicing applications can use as their speech
  22. service."""
  23.  
  24. __id__        = "$Id: httpserver.py 3882 2008-05-07 18:22:10Z richb $"
  25. __version__   = "$Revision: 3882 $"
  26. __date__      = "$Date: 2008-05-07 14:22:10 -0400 (Wed, 07 May 2008) $"
  27. __copyright__ = "Copyright (c) 2006-2008 Sun Microsystems Inc."
  28. __license__   = "LGPL"
  29.  
  30. import threading
  31. import BaseHTTPServer
  32.  
  33. import debug
  34. import platform
  35. import settings
  36. import speech
  37.  
  38. _httpRequestThread = None
  39.  
  40.  
  41. # Handlers for logging speech and braille output.
  42. #
  43. loggingFileHandlers = {}
  44. loggingStreamHandlers = {}
  45.  
  46. class _HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  47.     """Provides support for communicating with Orca via HTTP.  This is
  48.     mainly to support self-voicing applications that want to use Orca
  49.     as a speech service.
  50.  
  51.     The protocol is simple: POST content is 'stop', 'speak:<text>',
  52.     or 'isSpeaking'.
  53.  
  54.     To test this, run:
  55.  
  56.       wget --post-data='speak:hello world' localhost:20433
  57.  
  58.     """
  59.  
  60.     def log_request(self, code=None, size=None):
  61.         """Override to avoid getting a log message on stdout for
  62.         each GET, POST, etc. request"""
  63.         pass
  64.  
  65.     def do_GET(self):
  66.         self.send_response(200)
  67.         self.send_header("Content-type", "text/html")
  68.         self.end_headers()
  69.         self.wfile.write("<html><body><p>Orca %s</p></body></html>" \
  70.                          % platform.version)
  71.  
  72.     def do_POST(self):
  73.         contentLength = self.headers.getheader('content-length')
  74.         if contentLength:
  75.             contentLength = int(contentLength)
  76.             inputBody = self.rfile.read(contentLength)
  77.             debug.println(debug.LEVEL_FINEST,
  78.                           "httpserver._HTTPRequestHandler received %s" \
  79.                           % inputBody)
  80.             if inputBody.startswith("speak:"):
  81.                 speech.speak(inputBody[6:])
  82.                 self.send_response(200, 'OK')
  83.             elif inputBody == "stop":
  84.                 speech.stop()
  85.                 self.send_response(200, 'OK')
  86.             elif inputBody == "isSpeaking":
  87.                 self.send_response(200, 'OK')
  88.                 self.send_header("Content-type", "text/html")
  89.                 self.end_headers()
  90.                 self.wfile.write("%s" % speech.isSpeaking())
  91.         else:
  92.             debug.println(debug.LEVEL_FINEST,
  93.                           "httpserver._HTTPRequestHandler received no data")
  94.  
  95. class _HTTPRequestThread(threading.Thread):
  96.     """Runs a _HTTPRequestHandler in a separate thread."""
  97.  
  98.     def run(self):
  99.         """Try to start an HTTP server on settings.httpServerPort.
  100.         If this fails, retry settings.maxHttpServerRetries times,
  101.         each time incrementing the server port number by 1. If we
  102.         are still unable to start a server, just fail gracefully.
  103.         """
  104.  
  105.         portNo = settings.httpServerPort
  106.         connected = False
  107.         while not connected and \
  108.             (portNo < settings.httpServerPort + settings.maxHttpServerRetries):
  109.             try:
  110.                 httpd = BaseHTTPServer.HTTPServer(('', portNo),
  111.                                                   _HTTPRequestHandler)
  112.                 connected = True
  113.             except:
  114.                 if portNo == settings.httpServerPort:
  115.                     debug.printException(debug.LEVEL_WARNING)
  116.                 debug.println(debug.LEVEL_WARNING,
  117.                     "httpserver._HTTPRequestThread unable to start server " \
  118.                     "on port %d" % portNo)
  119.                 portNo += 1
  120.  
  121.         if not connected:
  122.             debug.println(debug.LEVEL_WARNING,
  123.                     "httpserver._HTTPRequestThread server startup failed.")
  124.         else:
  125.             httpd.serve_forever()
  126.  
  127. def init():
  128.     """Creates an HTTP server that listens for speak commands from a
  129.     separate port defined by settings.httpServerPort.  We run this
  130.     as a daemon so it will die automatically when orca dies."""
  131.  
  132.     global _httpRequestThread
  133.  
  134.     if settings.httpServerPort and (not _httpRequestThread):
  135.         try:
  136.             _httpRequestThread = _HTTPRequestThread()
  137.             _httpRequestThread.setDaemon(True)
  138.             _httpRequestThread.start()
  139.         except:
  140.             debug.printException(debug.LEVEL_WARNING)
  141.  
  142. def shutdown():
  143.     """Stops the HTTP server.  [[[WDW - not implemented yet.]]]"""
  144.     pass
  145.